package com.special.ResideMenuDemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Message.Product;
import Message.ProductManager;

public class MessageActivity extends ListActivity {
    private static final int DIALOG_EXIT=-1; // 代表按下返回键弹出的对话框
    // 定义ListView相关常量
    private static final int PAGESIZE=8;  // 每次取5条记录
    private int pageIndex=0;  // 用于保存当前是第几页，0代表第一页
    private ProductManager productManager=null;
    private List<Product> products = null;
    private static Map<Integer, Boolean> isSelected;
    private LayoutInflater mInflater = null;
    private Context context = null;
    private ListView lvProduct = null;
    private MyAdapter adapter = null;
    // 动态产生菜单
    private Menu myMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        productManager = new ProductManager();
        products = productManager.getProductByPager(pageIndex, PAGESIZE);
        if (products!=null) {
            System.out.println("Home"+products.size());
        }
//        setContentView(R.layout.activity_message);

        getActionBar().setTitle("消息");

        adapter = new MyAdapter(context);
        setListAdapter(adapter);

        lvProduct = getListView();
        lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (id == -1) {
//                    Toast.makeText(context, "添加新商品", Toast.LENGTH_SHORT).show();
//                } else if (id == -2) {
//                    adapter.more();
//                } else {
//                    Tool.ShowMessage(context, id+"");
//                    CheckBox chkIn = (CheckBox) view.findViewById(R.id.checkIn);
//                    if (chkIn != null) {
//                        chkIn.toggle();
//                        isSelected.put(position - 1, chkIn.isChecked());
//                    }
                    if (adapter.isBatchManager()) {
                        ViewHolder viewHolder = (ViewHolder) view.getTag();
                        viewHolder.checkBox.toggle();
                        isSelected.put(position, viewHolder.checkBox.isChecked());
                    }
//                }
            }
        });
    }

    // 触发返回键事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (adapter.isBatchManager()) {
                initUI(R.layout.productitem);
            } else {
                finish();
            }
            return true;
        }
        return false;
    }

    class MyAdapter extends BaseAdapter {
        private Context context;
        private int res_item_layout=R.layout.productitem;

        public MyAdapter(Context context) {
            super();
            System.out.println("Construct");
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); // 出错原因：NullPointException
            this.context = context;
        }

        public MyAdapter(Context context, int res_item_layout) {
            this.context = context;
            this.res_item_layout = res_item_layout;
            init();
        }

        public void init() {
            isSelected = new HashMap<Integer, Boolean>();
            for (int i = 0; i < products.size(); i++) {
                isSelected.put(i, false);
            }
        }

        @Override
        public int getCount() {
            return (products.size());
        }

        @Override
        public Object getItem(int position) {
            return products.get(position);
        }

        @Override
        public long getItemId(int position) {
//            return products.get(position).getId();
            if (position == 0) {
                return -1;
            } else if (position>0 && (position<this.getCount()-1)) {
                return products.get(position).getId();
            } else {
                return -2;
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            System.out.println("MyAdapter"+products.size());
            ViewHolder holder = null;

            if (convertView == null) {
                Log.d("convertView", position + ">>>>>>>>" + "null");
//                convertView = mInflater.inflate(R.layout.productitem, parent, false);
                holder = new ViewHolder();
                convertView = mInflater.inflate(this.res_item_layout, parent, false);
                holder.img = (ImageView) convertView.findViewById(R.id.imageView);
                holder.title = (TextView) convertView.findViewById(R.id.name);
                holder.unitPrice = (TextView) convertView.findViewById(R.id.price);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkIn);

                convertView.setTag(holder);
            } else {
                Log.d("convertView", position+">>>>>>>>"+"not null");
                holder = (ViewHolder) convertView.getTag();
            }
//            ImageView imgPhoto = (ImageView) convertView.findViewById(R.id.imageView);
            holder.img.setImageResource(products.get(position).getPhoto());
//            TextView txtName = (TextView) convertView.findViewById(R.id.name);
//            TextView txtUnitPrice = (TextView) convertView.findViewById(R.id.price);
            holder.title.setText(products.get(position).getName().toString());
            holder.unitPrice.setText(String.valueOf(products.get(position).getUnitPrice()));
//            CheckBox checkIn = (CheckBox) convertView.findViewById(R.id.checkIn);
            if (holder.checkBox != null) {
                holder.checkBox.setChecked(isSelected.get(position));
            }
            return convertView;
        }

        private void more() {
            // step1:当前页+1
            pageIndex++;
            System.out.println("pageIndex:" + pageIndex);
            // step2:获取更多的数据
            List<Product> moreProducts = productManager.getProductByPager(pageIndex, PAGESIZE);
            if (products.size()>pageIndex*PAGESIZE) {
                // step3:添加到现有的集合中
                products.addAll(moreProducts);
                // step4:刷新ListView
                this.notifyDataSetChanged();
            } else {
//                Toast.makeText(context, "无更多数据！", Toast.LENGTH_SHORT).show();
            }
        }

        public void refresh() {
            this.notifyDataSetChanged();
        }

        public boolean isBatchManager() {
            return this.res_item_layout == R.layout.productitemcheckbox;
        }

        public void changeUI(int res_item_layout) {
            this.res_item_layout = res_item_layout;
            this.notifyDataSetChanged();
        }
    }

    public final class ViewHolder {
        public ImageView img;
        public TextView title;
        public TextView unitPrice;
        public CheckBox checkBox;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        myMenu = menu;
        myMenu.clear();
        if (adapter.isBatchManager()) {
            myMenu.add(1, 4, 1, "全选").setIcon(R.drawable.manage);
            myMenu.add(1, 5, 2, "全消").setIcon(R.drawable.find);
            myMenu.add(1, 6, 3, "批量删除").setIcon(R.drawable.sort);
        } else {
            myMenu.add(1, 1, 1, "批量管理").setIcon(R.drawable.manage);
            myMenu.add(1, 2, 2, "搜索").setIcon(R.drawable.find);
            myMenu.add(1, 3, 3, "按姓名排序").setIcon(R.drawable.sort);
        }
        return true;
    }
    /*
    * 全选全消
    * @param isok true:全选;false:全消.
    * */
    private void isSelectedAll(boolean isok) {
        isSelected = new HashMap<Integer, Boolean>();
        for (int i = 0; i < products.size(); i++) {
            isSelected.put(i, isok);
        }
    }

    private boolean deleteList() {
        List<Integer> ids = new ArrayList<Integer>();
        for (int i = 0; i < products.size(); i++) {
            if (isSelected.get(i)) {
                ids.add(products.get(i).getId());
            }
        }

//        Tool.ShowMessage(context, ids.toString());

        return productManager.DelProduct(ids);

    }

    private void initUI(int res_ite_layout) {
        pageIndex = 0;
        adapter = new MyAdapter(context, res_ite_layout);
        setListAdapter(adapter);
        if (myMenu != null) {
            onCreateOptionsMenu(myMenu);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1: // 批量管理
//                Tool.ShowMessage(context, "批量管理");
//                adapter.changeUI(R.layout.productitemcheckbox);
                adapter = new MyAdapter(context, R.layout.productitemcheckbox);
                setListAdapter(adapter);
                if (myMenu != null) {
                    onCreateOptionsMenu(myMenu);
                }
                break;
            case 2: // 搜索
//                Tool.ShowMessage(context, "搜索");
                break;
            case 3: // 按价格排序
//                Tool.ShowMessage(context, "按价格排序");
                break;
            case 4: // 全选
//                Tool.ShowMessage(context, "全选");
                isSelectedAll(true);
                adapter.refresh();
                break;
            case 5: // 全消
//                Tool.ShowMessage(context, "全消");
                isSelectedAll(false);
                adapter.refresh();
                break;
            case 6: // 批量删除
                if (!hasSelected()) {
                    Toast.makeText(context, "请选择删除项！", Toast.LENGTH_SHORT).show();
                    break;
                }

                new AlertDialog.Builder(context).setIcon(R.drawable.icon).setTitle("Alert").setMessage("您确定要删除已选中列表么？").setPositiveButton("SURE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        boolean isok = deleteList();
                        if (isok) {
                            pageIndex = 0;
                            products = productManager.getProductByPager(pageIndex, PAGESIZE);
                            isSelected = new HashMap<Integer, Boolean>();
                            for (int i = 0; i < products.size(); i++) {
                                isSelected.put(i, false);
                            }
                            adapter.refresh();
                            Toast.makeText(context, "数据删除成功！", Toast.LENGTH_SHORT).show();
                            initUI(R.layout.productitem);
                        } else {
                            Toast.makeText(context, "数据删除失败！", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).setNegativeButton("CANCEL", null).create().show();
//                Tool.ShowMessage(context, "批量删除");
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private boolean hasSelected() {
        boolean _isSelected = false;
        for (int i = 0; i < products.size(); i++) {
            if (isSelected.get(i)) {
                _isSelected = true;
                break;
            }
        }
        return _isSelected;
    }
}
